package com.example.app.pages.main.home.accountList

import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.core.animateDpAsState
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.Search
import androidx.compose.material.pullrefresh.pullRefresh
import androidx.compose.material.pullrefresh.rememberPullRefreshState
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.RectangleShape
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.dp
import androidx.paging.compose.collectAsLazyPagingItems
import com.example.app.accountListViewModel
import com.example.app.barStateViewModel
import com.example.app.components.MyDivider.MyDivider
import com.example.app.components.MyDivider.MyDividerDirection
import com.example.app.components.MyIcon.MyNavigationIcon
import com.example.app.components.MyLazyColumn.MyLazyColumn
import com.example.app.components.MyLazyColumn.MyPageLazyColumn.MyPageLazyColumnBottom
import com.example.app.components.MyListItem.MyListItem
import com.example.app.components.MyNavigationBar.MyNavigationBar
import com.example.app.components.MyProgressIndicator.MyCustomPullRefreshIndicator
import com.example.app.components.MyScaffold.MyScaffoldHasTipAndLoading
import com.example.app.components.MySpacer.MySpacer
import com.example.app.components.MySurface.MySurface
import com.example.app.components.MyText.MyText
import com.example.app.components.MyTopBar.MyTopBar
import com.example.app.data.bean.routeAccount.AccountRecord
import com.example.app.pages.main.home.accountList.viewModel.AccountListViewModel
import com.example.app.routeViewModel
import com.example.app.ui.theme.middleSpacer
import com.example.app.ui.theme.my_description_color
import com.example.app.ui.theme.shapeLarge
import com.example.app.ui.theme.smallSpacer
import com.example.app.util.formatTimestamp
import com.example.app.viewmodel.BarStateViewModel
import com.example.app.viewmodel.MainViewModel
import com.example.app.viewmodel.RouteViewModel
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch

@OptIn(
    ExperimentalMaterial3Api::class,
    ExperimentalMaterialApi::class,
    ExperimentalFoundationApi::class
)
@Composable
fun AccountList() {
    //当前路由，显示标题用的
    var curHomeChild = routeViewModel.curHomeChild.collectAsState()
    //分页数据
    val accountRecordList = accountListViewModel.pagingDataFlow.collectAsLazyPagingItems()
    //lazyColumn滚动时的第一个item的index和offset
    val firstItemIndexAndOffset = accountListViewModel.firstItemIndexAndOffset.collectAsState()
    //刷新
    val refreshScope = rememberCoroutineScope()
    //是否在刷新
    var refreshing = accountListViewModel.refreshing.collectAsState()
    //刷新事件
    fun refresh() = refreshScope.launch {
        accountRecordList.refresh()
    }
    //下拉刷新
    val pullRefreshState = rememberPullRefreshState(
        refreshing.value,
        ::refresh,
    )
    //列表状态
    val listState = rememberLazyListState()
    //topbar的背景颜色显示与隐藏
    var topBarAlpha = accountListViewModel.topBarAlpha.collectAsState()
    //第一个item的高度，这里是广告的高度，初始高度
    val firstItemHeightDp by remember {
        mutableStateOf(250.dp)
    }
    //支出月预算高度
    var expenditureMonthlyBudgetedHeight = 70.dp
    //第一个item的高度，这里是广告的高度，初始高度
    val firstItemHeightPx = with(LocalDensity.current) {
        firstItemHeightDp.toPx()
    }
    //监听列表的状态
    LaunchedEffect(listState) {
        snapshotFlow { listState.firstVisibleItemIndex to listState.firstVisibleItemScrollOffset }.collect { (index, offset) ->
            //记录第一个的index和offset
            accountListViewModel.flowUpdate_firstItemIndexAndOffset(
                Pair(
                    index,
                    offset
                )
            )
            // 确保我们正在观察的是第一个item
            if (index == 0) {
                accountListViewModel.flowUpdate_topBarAlpha(
                    when {
                        offset <= 0 -> {
                            0f // 图像完全在视口中
                        }

                        offset >= firstItemHeightPx -> {
                            1f // 图像完全离开视口后，顶部栏完全不透明
                        }

                        else -> {
                            offset / firstItemHeightPx // 在过渡过程中，`topBarAlpha`随`offset`线性增加
                        }
                    }
                )
            } else {
                // 如果不是第一个item，保持顶部栏不透明
                accountListViewModel.flowUpdate_topBarAlpha(1f)
            }
        }
    }
    //topbar文字的颜色变化
    val topBarTitleColor by animateColorAsState(
        targetValue = if (topBarAlpha.value === 0f) MaterialTheme.colorScheme.surface else MaterialTheme.colorScheme.onPrimaryContainer
    )
    //topbar搜索图标的颜色变化
    val topBarSearchIconTint by animateColorAsState(
        targetValue = if (topBarAlpha.value === 0f) MaterialTheme.colorScheme.surface else MaterialTheme.colorScheme.onPrimaryContainer
    )
    //下拉刷新：下拉最大幅度
    var maxDragProgress by remember {
        mutableStateOf(0f)
    }
    //下拉刷新：页面下移动最大幅度
    val maxPageAnimatedOffset by remember(
        refreshing.value,
        pullRefreshState.progress
    ) {
        derivedStateOf {
            if (pullRefreshState.progress === 0f && refreshing.value === false) {
                maxDragProgress = 0f
                0f
            } else {
                //取最大的
                maxDragProgress = maxOf(
                    maxDragProgress,
                    pullRefreshState.progress
                )

                maxDragProgress
                //以下代码可以简化成上面一句话
                /*if (pullRefreshState.progress > maxDragProgress) {
                    maxDragProgress = pullRefreshState.progress
                    pullRefreshState.progress
                } else {
                    maxDragProgress
                }*/
            }
        }
    }
    //下拉刷新：页面下移量
    val pageAnimatedOffset by animateDpAsState(
        targetValue = (maxPageAnimatedOffset * 50).dp
    )
    val indicationIsVisible by remember(pullRefreshState.progress) {
        derivedStateOf {
            pullRefreshState.progress > 0 || refreshing.value === true
        }
    }
    //下拉刷新：refreshing的loading图标
    val indicationAnimatedOffset by animateDpAsState(
        targetValue = if (indicationIsVisible) {
            50.dp
        } else {
            -50.dp
        }
    )
    //状态栏随topbar的变化，而变化。
    if (topBarAlpha.value === 0f) {
        barStateViewModel.updateAll(
            isShowBottomBar = true,
            isStatusBarDarkIcon = false,
            statusBarColor = Color.Transparent,
            navigationBarColor = MaterialTheme.colorScheme.onPrimary,
            isNavigationBarDarkIcon = true
        )
    } else if (topBarAlpha.value === 1f) {
        barStateViewModel.updateAll(
            isShowBottomBar = true,
            isStatusBarDarkIcon = true,
            statusBarColor = MaterialTheme.colorScheme.background,
            navigationBarColor = MaterialTheme.colorScheme.onPrimary,
            isNavigationBarDarkIcon = true
        )
    }

    var curAccountRecord: AccountRecord? = null
    if (firstItemIndexAndOffset.value != null && accountRecordList.itemSnapshotList.items.size > 0) {
        curAccountRecord =
            accountRecordList.itemSnapshotList.items.get(firstItemIndexAndOffset.value!!.first)
    }

    MyScaffoldHasTipAndLoading(
        myScaffoldModifier = Modifier.pullRefresh(pullRefreshState),

        bottomBar = {
            //这个只是占位
            //通过这个占位 下面的 it.calculateBottomPadding() 才有效果
            MyNavigationBar {
            }
        }
    ) {
        var paddingValues = it
        MySurface(modifier = Modifier.padding(bottom = paddingValues.calculateBottomPadding())) {
            AccountListTopImage(
                height = firstItemHeightDp + pageAnimatedOffset,
                paddingValues = paddingValues,
                pageAnimatedOffset = pageAnimatedOffset
            )
            Box(
                modifier = Modifier
                    .fillMaxSize()
                    .offset(y = pageAnimatedOffset)
            ) {
                MyLazyColumn(state = listState) {
                    /*占位 bg*/
                    item {
                        Column(
                            modifier = Modifier
                                .clip(RectangleShape)
                                .height(firstItemHeightDp)
                        ) {
                            // MyFitImage(painterResourceId = R.drawable.bg4)
                        }
                    }
                    /*占位 空行*/
                    item {
                        MySpacer(
                            modifier = Modifier
                                .background(MaterialTheme.colorScheme.background)
                                .height(32.dp)
                                .fillMaxWidth()
                        )
                    }
                    //支出月预算
                    item {
                        AccountListTopItem(expenditureMonthlyBudgetedHeight)
                    }
                    /*占位 空行*/
                    item {
                        MySpacer(
                            modifier = Modifier
                                .background(MaterialTheme.colorScheme.background)
                                .height(middleSpacer)
                                .fillMaxWidth()
                        )
                    }
                    itemsIndexed(accountRecordList.itemSnapshotList.items) { index, item ->
                        AccountListItem(
                            item!!,
                            index,
                            accountRecordList.itemSnapshotList.items.toMutableList(),
                            accountListViewModel,
                            statusBarPadding = paddingValues.calculateTopPadding(),
                            topBarHeight = TopAppBarDefaults.TopAppBarExpandedHeight
                        )
                    }
                    //底部显示
                    item {
                        MyPageLazyColumnBottom(loadState = accountRecordList.loadState)
                    }
                }
                //topbar 顶部
                Row(
                    modifier = Modifier
                        .background(MaterialTheme.colorScheme.background.copy(alpha = topBarAlpha.value))
                        .fillMaxWidth()
                ) {
                    Column {
                        MyTopBar(
                            showDivider = false,
                            title = {
                                MyText(
                                    text = curHomeChild.value.title,
                                    color = topBarTitleColor
                                )
                            },
                            actions = {
                                MyNavigationIcon(
                                    imageVector = Icons.Rounded.Search,
                                    tint = topBarSearchIconTint,
                                    onClick = {

                                    }
                                )
                            })
                        //滚动分类
                        AnimatedVisibility(visible = topBarAlpha.value == 1f) {
                            var style = MaterialTheme.typography.bodySmall
                            MyListItem(
                                headlineContent = {
                                    if (curAccountRecord != null) {
                                        Row(
                                            horizontalArrangement = Arrangement.Start,
                                            verticalAlignment = Alignment.CenterVertically
                                        ) {
                                            Column(
                                            ) {
                                                MyText(
                                                    text = formatTimestamp(
                                                        curAccountRecord.CreateAt.toLong(),
                                                        "yyyy"
                                                    ),
                                                    style = style.copy(my_description_color)
                                                )
                                                MyText(
                                                    text = formatTimestamp(
                                                        curAccountRecord.CreateAt.toLong(),
                                                        "M"
                                                    ) + "月",
                                                    style = style
                                                )
                                            }
                                            MySpacer(modifier = Modifier.width(smallSpacer))
                                            Column(
                                                modifier = Modifier.weight(1f)
                                            ) {
                                                MyText(
                                                    text = "收 0.00",
                                                    style = style
                                                )
                                                MyDivider(
                                                    myDividerDirection = MyDividerDirection.HOR,
                                                    modifier = Modifier
                                                        .clip(RoundedCornerShape(2.dp))
                                                        .height(2.dp)
                                                        .background(MaterialTheme.colorScheme.primary)
                                                )
                                                MyText(
                                                    text = "支 15661.00",
                                                    style = style
                                                )
                                            }
                                            MySpacer(modifier = Modifier.width(smallSpacer))
                                            Column(
                                            ) {
                                                MyText(
                                                    text = "15661.00",
                                                    style = MaterialTheme.typography.bodyMedium
                                                )
                                                MyText(
                                                    text = "结余",
                                                    style = style.copy(my_description_color)
                                                )
                                            }
                                        }
                                    }
                                },
                                hasWrap = true,
                                myListItemWrapColumnBackgroundColor = Color.Transparent,
                                modifier = Modifier.clip(
                                    RoundedCornerShape(
                                        topStart = shapeLarge,
                                        topEnd = shapeLarge,
                                        bottomStart = 0.dp,
                                        bottomEnd = 0.dp
                                    )
                                ),
                            )
                        }
                    }
                }
            }
        }
    }
    //loading 加载 图标
    MyCustomPullRefreshIndicator(
        isIndicatorVisible = indicationIsVisible,
        indicatorOffsetY = indicationAnimatedOffset
    )
}
